package com.worldstear.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.worldstear.dao.PermissionMapper;
import com.worldstear.dao.RoleMapper;
import com.worldstear.dao.UserMapper;
import com.worldstear.model.Permission;
import com.worldstear.model.Role;
import com.worldstear.model.User;
import com.worldstear.service.LoginService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class LoginServiceImpl implements LoginService {
    final PermissionMapper permissionMapper;
    final RoleMapper roleMapper;
    final UserMapper userMapper;

    public LoginServiceImpl(UserMapper userMapper, RoleMapper roleMapper, PermissionMapper permissionMapper) {
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
        this.permissionMapper = permissionMapper;
    }

    @Override
    public User getUserByName(String name) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", name));
        List<Role> roles = roleMapper.selectList(new QueryWrapper<Role>().eq("user_id", user.getUserId()));

        List<Permission> permissions = permissionMapper.selectList(new QueryWrapper<Permission>().in("role_id", roles.stream().map(Role::getRoleId).toArray()));
        Map<Long, List<Permission>> groupByRoleIdPermissionMap = permissions.stream().collect(Collectors.groupingBy(Permission::getRoleId));
        groupByRoleIdPermissionMap.forEach((k,v) -> roles.forEach(i -> {
            if(Objects.equals(i.getRoleId(), k)) {
                i.setPermissions(v);
            }
        }));
        user.setRoles(roles);
        return user;
    }
}
